﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Tools.Ribbon;
using System.Windows.Forms;
using DTO;
using BUS;
using System.IO;
using Microsoft.Office.Interop.Word;
using Microsoft.Office.Tools.Word;

namespace ourAdd_in
{
    public partial class RibMaHoa : OfficeRibbon
    {
        string email = "";
        public RibMaHoa()
        {
            InitializeComponent();
             
        }

        private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
        {

        }

        private void btnLogin_Click(object sender, RibbonControlEventArgs e)
        {
            frmLogIn f = new frmLogIn();
            f.OnLogIn+=new frmLogIn.logIn_FireRibbon(f_OnLogIn);
            if (f.ShowDialog()==DialogResult.OK)
            {
                BUS.AccountBUS bus = new BUS.AccountBUS();
                AccountDTO dt = bus.GetAccountInfo(email);
                //thong bao ten
                //tabMyAddIn.Label = dt.Name + "- Email: " + dt.Email;
            }
        }

        private void f_OnLogIn(string Email)
        {
            email = Email;
            groupEn_De.Visible = true;
            groupSign.Visible = true;
        }

        private void btnRegister_Click(object sender, RibbonControlEventArgs e)
        {
            Form f = new frmRegister();
            if (f.ShowDialog()==DialogResult.OK)
            {

            }

        }

        private void btnUpdate_Click(object sender, RibbonControlEventArgs e)
        {
            Form f = new frmUpdate();
            f.Show();
        }



        private void btnToXML_Click(object sender, RibbonControlEventArgs e)
        {
            BUS.AccountBUS bus = new BUS.AccountBUS();
            AccountDTO account = bus.GetAccountInfo(email);
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "XML file (*.xml)|*xml";
            dlg.FileName = email + ".xml";
            // dlg.CheckFileExists = true;
            string directory = "C:\\AccountInfo";
            if (!System.IO.Directory.Exists(directory))
                System.IO.Directory.CreateDirectory("C:\\AccountInfo");
            dlg.InitialDirectory = "C:\\AccountInfo";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                bus.ExportToXML(dlg.FileName, account);
            }
        }

        private void btnFromXML_Click(object sender, RibbonControlEventArgs e)
        {
            BUS.AccountBUS bus = new BUS.AccountBUS();
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "XML file (*xml)|*xml";
            string filePath = "";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                if (dlg.FileName != null)
                {
                    filePath = dlg.FileName;
                    if (bus.ImportFromXML(filePath))
                        MessageBox.Show("Import successfully!");
                    else
                        MessageBox.Show("Import failed!");
                }
            }

        }

        private void btnSign_Click(object sender, RibbonControlEventArgs e)
        {
            frmPassForPrivateKey form = new frmPassForPrivateKey(email);
            form.OnGetKey += new frmPassForPrivateKey.getKey(f_openSign);
            form.Show();
        }

        private void f_openSign()
        {
            Microsoft.Office.Interop.Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument;
            String filePathName = System.Windows.Forms.Application.StartupPath + "\\SignWordAddin.docx";
            string fileCopy = System.Windows.Forms.Application.StartupPath + "\\SignWordAddin_Copy.docx";
            DocumentSaveAs(filePathName, doc);
            if (File.Exists(fileCopy)) File.Delete(fileCopy);
            File.Copy(filePathName, fileCopy);

            SignData(fileCopy);

            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "sig files (*.sig)|*.sig|All files (*.*)|*.*";
            dlg.FilterIndex = 1;
            dlg.RestoreDirectory = true;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                if (File.Exists(fileCopy + ".sig"))
                {
                    //File.Copy(fileCopy + ".sig", dlg.FileName);
                    string pathName = Path.GetDirectoryName(dlg.FileName);
                    string fileName = Path.GetFileNameWithoutExtension(dlg.FileName);
                    File.Copy(fileCopy, pathName + "\\" + fileName + ".docx");
                    File.Copy(fileCopy + ".sig", pathName + "\\" + fileName + ".docx.sig");
                    MessageBox.Show("Data Signed Successful!");
                }
            }
        }

        private void SignData(string file)
        {
            byte[] data = File.ReadAllBytes(file);
            BUS.AccountBUS bus = new BUS.AccountBUS();
            AccountDTO account = bus.GetAccountInfo(email);
            byte[] signature = BUS.OurRSA.HashAndSign(data, account.PrivateKey);
            using (Stream s = File.Create(file + ".sig"))
            {
                s.Write(signature, 0, signature.Length);
            }
        }

        private void button1_Click(object sender, RibbonControlEventArgs e)
        {
            Microsoft.Office.Interop.Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument;
            doc.ActiveWindow.Selection.WholeStory();
            doc.ActiveWindow.Selection.Copy();

            IDataObject data = Clipboard.GetDataObject();

            //Do whatever with the text.
            string text = data.GetData(DataFormats.Text).ToString();
            MessageBox.Show(text);
        }

        private void btnEncrypt_Click(object sender, RibbonControlEventArgs e)
        {
            groupEcryptOption.Visible = true;
            BUS.AccountBUS bus=new BUS.AccountBUS();
            List<AccountDTO> list = bus.GetAllAccountInfo();
            foreach (var item in list)
            {
                RibbonDropDownItem dropdownItem = new RibbonDropDownItem();
                dropdownItem.Label = item.Email;
                th_Receiver.Items.Add(dropdownItem);
            }
        }

        private void DocumentSaveAs(string filePathName,Microsoft.Office.Interop.Word.Document doc)
        {
            object FileName = filePathName;
            object FileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLDocument;
            object LockComments = false;
            object AddToRecentFiles = true;
            object ReadOnlyRecommended = false;
            object EmbedTrueTypeFonts = false;
            object SaveNativePictureFormat = true;

            //////////////////////////////////////////////////////////////////////////
            //Chinh thành false
            object SaveFormsData = false;
            //////////////////////////////////////////////////////////////////////////
            object SaveAsAOCELetter = false;
            object Encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;
            object InsertLineBreaks = false;
            object AllowSubstitutions = false;
            object LineEnding = Microsoft.Office.Interop.Word.WdLineEndingType.wdCRLF;
            object AddBiDiMarks = false;
            object missing = System.Type.Missing;


            if (doc.SaveFormat == (int)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLDocument)
            {
                doc.SaveAs(ref FileName, ref FileFormat, ref LockComments,
                    ref missing, ref AddToRecentFiles, ref missing,
                    ref ReadOnlyRecommended, ref EmbedTrueTypeFonts,
                    ref SaveNativePictureFormat, ref SaveFormsData,
                    ref SaveAsAOCELetter, ref Encoding, ref InsertLineBreaks,
                    ref AllowSubstitutions, ref LineEnding, ref AddBiDiMarks);
            }
        }

        private void btnOpenFile_Click(object sender, RibbonControlEventArgs e)
        {
            //Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument;
            DocumentSaveAs(@"D:\khiem.docx",doc);
            //doc.ActiveWindow.Selection.WholeStory();
            //MessageBox.Show(doc.ActiveWindow.Selection.FormattedText.Text);
            //IDataObject data = Clipboard.GetDataObject();

            //Do whatever with the text.
            //string text = data.GetData(DataFormats.Text).ToString();
            //MessageBox.Show(text);
            //DocumentSaveAs(doc);
        }

        private void Encrypt(string FilePath)
        {
            byte[] Key = null;
            byte[] IV = null;

            #region mã hóa file
            int SymAlgo = th_SymAlgo.SelectedItemIndex+1;
            int cm = this.th_CihperMode.SelectedItemIndex+1;
            int pm = this.th_PaddingMode.SelectedItemIndex+1;
            string email = this.th_Receiver.SelectedItem.Label;
            BUS.AccountBUS bus=new BUS.AccountBUS();
            AccountDTO acc = bus.GetAccountInfo(email);
            string receiverPublicKey = acc.PublicKey;

            if (FilePath.Length > 0 && File.Exists(FilePath))
            {
                try
                {

                    byte[] plainBytes = File.ReadAllBytes(FilePath);
                    byte[] cipherBytes = OurSymAlgo.Encrypt(plainBytes, ref Key, ref IV, cm, pm, SymAlgo, receiverPublicKey);

                    using (Stream s = File.Create(FilePath + ".enc"))
                    {
                        s.Write(cipherBytes, 0, cipherBytes.Length);
                    }
                    //MessageBox.Show("File Encrypted Successfully");

                }
                catch (Exception ex)
                {

                    MessageBox.Show(ex.ToString());
                }
            }
            else
            {
                MessageBox.Show("File not found!");
            }
            #endregion

        }

        private void btnStartEncrypt_Click(object sender, RibbonControlEventArgs e)
        {
            Microsoft.Office.Interop.Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument;
            String filePathName = System.Windows.Forms.Application.StartupPath+"\\EncryptWordAddin.docx";
            string fileCopy = System.Windows.Forms.Application.StartupPath+"\\EncryptWordAddin_Copy.docx";
            DocumentSaveAs(filePathName, doc);
            if (File.Exists(fileCopy)) File.Delete(fileCopy);
            File.Copy(filePathName, fileCopy);
            Encrypt(fileCopy);
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "enc files (*.enc)|*.enc|All files (*.*)|*.*";
            dlg.FilterIndex = 1;
            dlg.RestoreDirectory = true;
            if (dlg.ShowDialog()==DialogResult.OK)
            {
                if (File.Exists(fileCopy+".enc"))
                {
                    File.Copy(fileCopy + ".enc", dlg.FileName);
                    MessageBox.Show("Encrypt Successful!");
                }
            }
        }

        private void btnDecrypt_Click(object sender, RibbonControlEventArgs e)
        {
            frmPassForPrivateKey frm = new frmPassForPrivateKey(email);
            frm.OnGetKey += new frmPassForPrivateKey.getKey(f_OnGetKey);
            frm.Show();
        }

        void f_OnGetKey()
        {
            AccountBUS bus = new AccountBUS();
            AccountDTO account = bus.GetAccountInfo(email);
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "enc files (*.enc)|*.enc|All files (*.*)|*.*";
            dlg.FilterIndex = 1;
            dlg.RestoreDirectory = true;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                if (dlg.FileName != null)
                {
                    // truyen tren file cho bus
                    //bus.GiaiMa()
                    //BUS.OurSymAlgo bus = new BUS.OurSymAlgo();
                    byte[] decryptedBytes = { };
                    decryptedBytes = OurSymAlgo.Decrypt(dlg.FileName, account.PrivateKey);
                    SaveDecryptedFile(decryptedBytes, dlg.FileName);
                }
            }
        }

        void SaveDecryptedFile(byte[] decryptedBytes, string filePath)
        {
            if (File.Exists(filePath) && Path.GetExtension(filePath) == ".enc")
            {
                SaveFileDialog dlg = new SaveFileDialog();
                string directory = "C:\\Decrypted Files";
                if (!System.IO.Directory.Exists(directory))
                    System.IO.Directory.CreateDirectory(directory);
                dlg.InitialDirectory = directory;
                dlg.FileName = Path.GetFileNameWithoutExtension(filePath);
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    //
                    try
                    {
                        using (Stream s = File.Create(dlg.FileName))
                        {
                            s.Write(decryptedBytes, 0, decryptedBytes.Length);
                        }
                        MessageBox.Show("File Decrypted Successfully");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
            }
            else
            {
            }


        }

        private void btnVerify_Click(object sender, RibbonControlEventArgs e)
        {
            f_openVerify();
        }
        private void f_openVerify()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "doc files (*.doc)|*.doc|docx files (*.docx)|*.docx|All files (*.*)|*.*";
            dlg.FilterIndex = 1;
            dlg.RestoreDirectory = true;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                OpenFileDialog dlgOpenFileSign = new OpenFileDialog();
                dlgOpenFileSign.Filter = "sig files (*.sig)|*.sig";
                dlgOpenFileSign.RestoreDirectory = true;
                string fileSignName = "";
                if (dlgOpenFileSign.ShowDialog() == DialogResult.OK)
                {
                    fileSignName = dlgOpenFileSign.FileName;
                }
                else
                {
                    fileSignName = dlg.FileName + ".sig";
                }

                if (!File.Exists(fileSignName))
                {
                    MessageBox.Show("Not Found Signature");
                    return;
                }
                byte[] data = File.ReadAllBytes(dlg.FileName);
                byte[] signature = File.ReadAllBytes(fileSignName);
                BUS.AccountBUS bus = new BUS.AccountBUS();
                List<AccountDTO> list = bus.GetAllAccountInfo();
                foreach (var item in list)
                {
                    if (BUS.OurRSA.VerifyHash(data, signature, item.PublicKey))
                    {
                        frmAccountInfo form = new frmAccountInfo();
                        string _info = "";
                        _info += "Name: " + item.Name + "\r\n";
                        _info += "Phone: " + item.Phone + "\r\n";
                        _info += "Email: " + item.Email + "\r\n";
                        _info += "Address: " + item.Address + "\r\n";
                        form._info = _info;
                        form.Show();
                    }
                }
            }
            else
            {

            }
        }

    }
}
